package com.fly.caihong.activity;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.fly.caihong.R;
import com.fly.caihong.base.BaseActivity;
import com.fly.caihong.model.LUser;
import com.fly.caihong.utils.KeyboardUtils;
import com.fly.caihong.utils.ToastUtils;

import org.litepal.crud.DataSupport;

public class RegisterActivity extends BaseActivity {

    private EditText mEdtName, mEdtPwd, mEdtPwdConfirm;
    private Button mBtnRegister;

    @Override
    protected int getLayout() {
        return R.layout.activity_register;
    }

    @Override
    protected void initViews() {
        super.initViews();
        mToolbar.setMainTitle("注册");
        mEdtName = findViewById(R.id.edt_name);
        mEdtPwd = findViewById(R.id.edt_pwd);
        mEdtPwdConfirm = findViewById(R.id.edt_pwd_confirm);
        mBtnRegister = findViewById(R.id.btn_register);
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        mBtnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mEdtName.getText().toString().equals("")) {
                    ToastUtils.showLong("请输入用户名");
                    return;
                }
                if (mEdtPwd.getText().toString().equals("")) {
                    ToastUtils.showLong("请输入密码");
                    return;
                }
                if (mEdtPwdConfirm.getText().toString().equals("")) {
                    ToastUtils.showLong("请再次输入密码");
                    return;
                }
                if (!mEdtPwd.getText().toString().equals(mEdtPwdConfirm.getText().toString())) {
                    ToastUtils.showLong("二次输入的密码不一致");
                    return;
                }
                boolean userNameExist = DataSupport.isExist(LUser.class
                        , "userName=?", mEdtName.getText().toString());
                if (userNameExist) {
                    ToastUtils.showLong("用户名已存在");
                    return;
                }
                KeyboardUtils.hideSoftInput(RegisterActivity.this);
                showLoading("正在注册,请稍候...");
                mBtnRegister.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoading();
                        LUser user = new LUser();
                        user.setUserName(mEdtName.getText().toString());
                        user.setPassword(mEdtPwd.getText().toString());
                        user.save();
                        ToastUtils.showLong("注册成功");
                        finish();
                    }
                }, 2000);
            }
        });
    }
}
